package com.dhh.toodledo.util;


import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import com.dhh.toodledo.model.AccountInfo;
import com.dhh.toodledo.model.Task;
import com.dhh.toodledo.model.Tasks;

public class HttpUtil {
	public static String appID = "toodledo4android";
	public static String appToken = "api4f8bb2500e3f2";
	
	public static String lookupAccount(String email,String password)throws Exception{
		String userId = null;
		String sig = MD5(email+appToken);
		String url = "http://api.toodledo.com/2/account/lookup.php?appid="+appID+";sig="+sig+";email="+email+";pass="+password;
		String json = handleGetRequest(url);
		JSONObject obj = new JSONObject(json);
		userId = obj.getString("userid");
		return userId;
	}
	
	public static String getSessionToken(String userid) throws Exception{
		String token = null;
		String sig = MD5(userid+appToken);
		String url = "http://api.toodledo.com/2/account/token.php?userid="+userid+";appid="+appID+";sig="+sig;
		String json = handleGetRequest(url);
		JSONObject obj = new JSONObject(json);
		token = obj.getString("token");		
		return token;
	}
	
	public static Task getTask(String key,String id) throws Exception{
		String url = "http://api.toodledo.com/2/tasks/get.php?key="+key+";id="+id+";fields=folder,star,priority,startdate,duedate,note";
		String json = handleGetRequest(url);
		Tasks tasks = JsonUtil.parseTasks(json);
		Task task = tasks.getNum()>0 ? tasks.getTasks().get(0):null;		
		return task;
	}
	
	public static List<Task> getTasks(String key,String start) throws Exception{
		String url = "http://api.toodledo.com/2/tasks/get.php?key="+key+";num=25;start="+start+";comp=0;fields=star,priority,startdate,duedate";
		String json = handleGetRequest(url);
		Tasks tasks = JsonUtil.parseTasks(json);
		List<Task> tlst = new ArrayList<Task>();
		if(tasks.getNum()>0)
			tlst.addAll(tasks.getTasks());
		return tlst;
	}
	
	public static List<Task> getAllTasks(String key) throws Exception{
		String url = "http://api.toodledo.com/2/tasks/get.php?key="+key+";comp=0;fields=star,priority,startdate,duedate";
		String json = handleGetRequest(url);
		Tasks tasks = JsonUtil.parseTasks(json);
		List<Task> tlst = new ArrayList<Task>();
		if(tasks.getNum()>0)
			tlst.addAll(tasks.getTasks());
		return tlst;
	}
	
	public static List<Task> getHotTasks(String key,int hotlistduedate,int hotlistpriority,int hotliststatus,int hotliststar) throws Exception{
		String url = "http://api.toodledo.com/2/tasks/get.php?key="+key+";comp=0;fields=star,priority,startdate,duedate,status";
		String json = handleGetRequest(url);
		Tasks tasks = JsonUtil.parseTasks(json);
		List<Task> tlst = new ArrayList<Task>();
		Calendar c1 = Calendar.getInstance();
		long time = c1.getTimeInMillis() + Long.valueOf(hotlistduedate) * 24 * 3600 * 1000;
		c1.setTimeInMillis(time);
		
		Calendar c2 = Calendar.getInstance();
		
		if(tasks.getNum()>0)
			for(Task t : tasks.getTasks()){
				boolean isStart = t.getStartdate()<= Long.valueOf(CUtil.getStamp(c2.getTime()));
				boolean isPri = t.getPriority().intValue()==hotlistpriority;
				boolean isDue = t.getDuedate().longValue() < Long.valueOf(CUtil.getStamp(c1.getTime()));
				boolean isStar = t.getStar().intValue() == hotliststar;
				if(isStart && (isPri || isDue || isStar)){
					tlst.add(t);
				}
			}
		return tlst;
	}
	
	public static List<Task> getAllTasks(String key,String star) throws Exception{
		String url = "http://api.toodledo.com/2/tasks/get.php?key="+key+";comp=0;fields=star,priority,startdate,duedate";
		String json = handleGetRequest(url);
		Tasks tasks = JsonUtil.parseTasks(json);
		List<Task> tlst = new ArrayList<Task>();
		if(tasks.getNum()>0)
			for(Task t : tasks.getTasks()){
				if(Long.valueOf(star).intValue()==t.getStar().intValue()){
					tlst.add(t);
				}
			}
		return tlst;
	}
	
	public static List<Task> getTaskComp(String key) throws Exception{
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		int todayTime = Integer.valueOf(CUtil.getStamp(c.getTime()));	
		
		String url = "http://api.toodledo.com/2/tasks/get.php?key="+key+";modafter="+todayTime+";comp=1;fields=star,priority,startdate,duedate";
		String json = handleGetRequest(url);
		Tasks tasks = JsonUtil.parseTasks(json);
		List<Task> tlst = new ArrayList<Task>();
		if(tasks.getNum()>0)
			tlst.addAll(tasks.getTasks());
		return tlst;
	}
	
	public static String generateKey(String userPassword,String sessionToken){
		return MD5(MD5(userPassword)+appToken+sessionToken );
	}
	
	public static AccountInfo getAccountInfo(String key) throws Exception{
		String url = "http://api.toodledo.com/2/account/get.php?key="+key;
		String resp = handleGetRequest(url);
		AccountInfo account = JsonUtil.parseAccount(resp);
		return account;
	}
	
	private static String MD5(String md5) {
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			byte[] array = md.digest(md5.getBytes());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
			}
			return sb.toString();
		} catch (java.security.NoSuchAlgorithmException e) {
		}
		return null;
	}
	
	private static String handleGetRequest(String url) throws Exception{
		String resp = "";

		HttpClient httpclient = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		resp = httpclient.execute(request, responseHandler);
	
		return resp;
	}
	
	public static String addTask(String key,JSONObject task) throws Exception{
		String resp = "";

		String p =  URLEncoder.encode(task.toString(), "UTF-8");
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://api.toodledo.com/2/tasks/add.php?key="+key+";tasks="+p);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		resp = httpclient.execute(post, responseHandler);
		System.out.println(resp);
	
		return resp;
	}
	
	public static String updateTask(String key,JSONObject task) throws Exception{
		String resp = "";

		String p =  URLEncoder.encode(task.toString(), "UTF-8");
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://api.toodledo.com/2/tasks/edit.php?key="+key+";tasks="+p+";fields=star,startdate,duedate,note,priority");
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		resp = httpclient.execute(post, responseHandler);
		System.out.println(resp);
	
		return resp;
	}
	
	public static String deleteTask(String key,JSONObject task) throws Exception{
		String resp = "";

		String p =  URLEncoder.encode("["+task.getString("id")+"]", "UTF-8");
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://api.toodledo.com/2/tasks/delete.php?key="+key+";tasks="+p);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		resp = httpclient.execute(post, responseHandler);
	
		return resp;
	}
}
